package gsw.tool.http.chain;

import android.util.Log;

import java.io.IOException;

import gsw.tool.http.HttpClient;
import gsw.tool.http.Response;
import gsw.tool.http.connection.HttpConnection;
import gsw.tool.http.request.HttpUrl;
import gsw.tool.http.request.Request;

/**
 * 通过Socket创建Http连接，使用连接池来获取Http连接
 */
public class InterceptorConnection implements Interceptor {
    @Override
public Response intercept(InterceptorChain chain) throws IOException {
    Log.e("interceprot","连接拦截器....");
    Request request = chain.call.request();
    HttpClient client = chain.call.client();
    HttpUrl url = request.url();
    String host = url.getHost();
    int port = url.getPort();
    HttpConnection connection = client.connectionPool().get(host, port);
    if (null == connection) {
        connection = new HttpConnection();
    } else {
        Log.e("call", "使用连接池......");
    }
    connection.setRequest(request);
    try {
        //调用下一个拦截器
        Response response = chain.proceed(connection);
        if (response.isKeepAlive()) {
            client.connectionPool().put(connection);
        }
        return response;
    } catch (IOException e) {
        throw e;
    }
}
}
